function parseLocaleHtmlEntities(string) {
    if (typeof string == "string") {
        return string.replace(/&aacute;/g, "a").replace(/&eacute;/g, "e").replace(/&iacute;/g, "i").replace(/&oacute;/g, "o").replace(/&uacute;/g, "u");
    }
    return string;
}

function paintGooglePieChart(container, chartdata) {
    dojo.style(container.parentNode, "padding", "0");
    var edge = Math.max(Math.floor(dojo.style(container, "width")), 205);
    var url = "http://chart.apis.google.com/chart?chs=" + edge + "x" + Math.floor(dojo.style(container, "height") - 3) + "&cht=p3&chd=t:";
    var labels = "&chl=";
    var legend = "&chdl=";
    for (var index = 0; index < chartdata.length; index++) {
        url += chartdata[index].y + ",";
        legend += parseLocaleHtmlEntities(chartdata[index].legend) + "|";
        labels += chartdata[index].text + "|";
    }
    var img = new Image();
    img.src = url.substring(0, url.length - 1) + labels.substring(0, labels.length - 1) + legend.substring(0, legend.length - 1) + "&chdlp=b&chco=" + getChartColor();
    container.appendChild(img);
}

function getSecondChartColor() {
    return currentTheme == "nihilo" ? "404040" : currentTheme == "soria" ? "404040" : "A0A0A0";
}

function joinProject() {
    var grid = dijit.byId("gridallProjects");
    if (grid.selection.selectedIndex >= 0) {
        var selected = grid.selection.getSelected();
        if (selected && selected[0]) {
            var id = dojo.isArray(selected[0].id) ? selected[0].id[0] : selected[0].id;
            DefaultProjectManager.joinProject(id, function() {
                updateDashboardGrids();
                dojo.style(byId("joinProjectIcon"), "opacity", "0.5");
            });
        }
    }
}

function changeNewProjectServerType(id) {
    var server = dijit.byId("serverType" + id).getValue();
    dojo.style(dojo.byId("newProjectServerDetails" + id), "display", server == "NullSCM" ? "none" : "inline-block");
}

function resetProjectData(id) {
    dijit.byId("projectType" + id).reset();
    dijit.byId("serverType" + id).reset();
    dijit.byId("relativePath" + id).reset();
    dojo.byId("connectionDetails" + id).value = "";
    dijit.byId("connectionDetails" + id + "0").reset();
    dijit.byId("save" + id).setDisabled(true);
    dijit.byId("check" + id).setDisabled(false);
    dijit.byId("projectName" + id).reset();
    dijit.byId("description" + id).reset();
    dijit.byId("currentVersion" + id).reset();
    dijit.byId("homePage" + id).reset();
    dojo.byId("validationWarningContainer").innerHTML = "";
    dojo.style(dojo.byId("newProjectServerDetails" + id), "display","none");
    dojo.style(dojo.byId("newProjectFreeFormDetails" + id), "display","none");
}

function changeNewProjectType(id) {
    var type = dijit.byId("projectType" + id).getValue();
    dojo.style(dojo.byId("newProjectFreeFormDetails" + id), "display", type == "1" ? "inline-block" : "none");
}

function getProjectData(id, projectClass, connectionDetailsClass) {
    return dwr.engine.remote.newObject(projectClass, {
        projectType: dijit.byId("projectType" + id).getValue(),
        serverType: dijit.byId("serverType" + id).getValue(),
        relativePath: dijit.byId("relativePath" + id).getValue(),
        homePage: dijit.byId("homePage" + id).getValue(),
        projectName: dijit.byId("projectName" + id).getValue(),
        description: dijit.byId("description" + id).getValue(),
        connectionDetails: getProjectConnectionDetails(id, connectionDetailsClass)
    });
}

function getProjectConnectionDetails(id, connectionDetailsClass) {
    var connectionId = dojo.byId("connectionDetails" + id).value;
    return connectionId ? dwr.engine.remote.newObject(connectionDetailsClass, {id: connectionId}) : null;
}

function createProject(id, projectClass, connectionDetailsClass) {
    var projectData = getProjectData(id, projectClass, connectionDetailsClass);
    DefaultProjectManager.createProject(projectData, dijit.byId("currentVersion" + id).getValue(), function(data) {
        closePopup("newprojectform");
        updateDashboardGrids();
    });
}

function validateProjectData(id, projectClass, connectionDetailsClass) {
    var projectData = getProjectData(id, projectClass, connectionDetailsClass);
    DefaultProjectManager.validateProject(projectData, dijit.byId("currentVersion" + id).getValue(), {
        callback : function(data) {
            if (data) {
                dijit.byId("check" + id).setDisabled(false);
                dojo.byId("validationWarningContainer").innerHTML = "<span><img style='height:20px;vertical-align:middle;padding-right:3px' src='" + contextPath + "/resource.iwebmvc?file=/images/cancelupload_soria.png" + "' alt='Error' />" + data + "</span>";
            } else {
                dijit.byId("save" + id).setDisabled(false);
                dojo.byId("validationWarningContainer").innerHTML = "";
            }
        },
        errorHandler: function(message) {
            dijit.byId("check" + id).setDisabled(false);
            dojo.byId("validationWarningContainer").innerHTML = "<span><img style='height:20px;vertical-align:middle;padding-right:3px' src='" + contextPath + "/resource.iwebmvc?file=/images/alert.gif" + "' alt='Error' />" + message + "</span>";
        }
    });
}

function editProjectSettings(project, alias) {
    var name = dijit.byId("projectName" + alias).getValue();
    var newalias = dijit.byId("alias" + alias).getValue();
    var description = dijit.byId("description" + alias).getValue();
    var homePage = dijit.byId("homePage" + alias).getValue();
    var publicView = dijit.byId("publicView" + alias).getValue() == "on";
    var doc = dojo.byId("logo" + alias).value;
    DefaultProjectManager.editProjectSettings(project, name, newalias, description, homePage, doc, publicView, function() {
        closePopup(alias);
        byId(alias + "name").innerHTML = name;
        var imgLogo = byId(alias + "logo");
        if (imgLogo) {
            imgLogo.src = contextPath + "resource.iwebmvc?file=" + (doc ? doc : "/images/nologo.jpg");
        }
        updateDashboardGrids();
    });
}

function updateTreeData(module, name, desc, treedata, model) {
    for (var item = 0; item < treedata.length; item++) {
        var data = treedata[item];
        if (data.id == module) {
            if (dojo.isArray(data.moduleName)) data.moduleName[0] = name;
            else data.moduleName = name;
            if (dojo.isArray(data.description)) data.description[0] = desc;
            else data.description = desc;
            model.onChange(data);
        } else if (data.children) updateTreeData(module, name, desc, data.children, model);
    }
}

function changeModule(module, name, desc, treedata, model, alias) {
    dijit.byId(alias + "modulesSaveLoading").setDisabled(true);
    dojo.style(byId(alias + "modulesSaveLoadingContainer"), "display", "");
    DefaultProjectManager.changeModule(module, name, desc, function() {
        dijit.byId(alias + "modulesSaveLoading").setDisabled(false);
        dojo.style(byId(alias + "modulesSaveLoadingContainer"), "display", "none");
        updateTreeData(module, name, desc, treedata.items[0].children, model);
    });
}

function updateNewTreeData(id, module, name, desc, treedata, model) {
    for (var index = 0; index < treedata.length; index++) {
        var data = treedata[index];
        if (data.id == module) {
            var item = {
                id: [id], sequence: [20000 + Math.floor(Math.random() * 1000)], moduleName: [name], description: [desc],
                _S: data._S, level: [dojo.isArray(data.level) ? data.level[0] : data.level]
            };
            if (dojo.isArray(data.children)) data.children.push(item);
            else data.children = [item];
            item._S._arrayOfAllItems[item._0] = item;
            model.onChildrenChange(data, data.children);
        } else if (data.children) updateNewTreeData(id, module, name, desc, data.children, model);
    }
}

function newComponent(project, module, name, desc, treedata, model, level, alias) {
    if (level < 2) {
        dijit.byId(alias + "modulesNewLoading").setDisabled(true);
        dojo.style(byId(alias + "modulesNewLoadingContainer"), "display", "");
        DefaultProjectManager.createModule(project, level == -1 ? null : module, name, desc, function(id) {
            dijit.byId(alias + "modulesNewLoading").setDisabled(false);
            dojo.style(byId(alias + "modulesNewLoadingContainer"), "display", "none");
            if (level == -1) {
                var item = {
                    id: [id], sequence: [10000+Math.floor(Math.random()*1000)], moduleName: [name], description: [desc],
                    _S: treedata.items[0]._S, level: [0]
                };
                treedata.items[0].children.push(item);
                item._S._arrayOfAllItems[item._0] = item;
                model.onChildrenChange(treedata.items[0], treedata.items[0].children);
            } else {
                updateNewTreeData(id, module, name, desc, treedata.items[0].children, model);
            }
            updateDashboardGrids();
        });
    }
}

function addMember(alias, project, data, model) {
    var user = dojo.byId("developers" + alias).value;
    if (user) {
        var name = dijit.byId("developers" + alias + "0").getValue();
        dijit.byId(alias + "membership").setDisabled(true);
        dojo.style(byId(alias + "membershipNewLoadingContainer"), "display", "");
        var adm = dijit.byId(alias + "MembershipType").getValue();
        DefaultProjectManager.addProjectMember(project, user, adm != 0, function(result) {
            dijit.byId(alias + "membership").setDisabled(false);
            dojo.style(byId(alias + "membershipNewLoadingContainer"), "display", "none");
            if (result) {
                var id = 50 + Math.floor(Math.random() * 100);
                if (adm == 0) id = id * 10000;
                var item = {name: [name], sequence: [id], _0: id, _S: data.items[0]._S};
                item._S._arrayOfAllItems[item._0] = item;
                data.items[0].children[adm == 0 ? 1 : 0].children.push(item);
                model.onChildrenChange(data.items[0].children[adm == 0 ? 1 : 0], data.items[0].children[adm == 0 ? 1 : 0].children);
                refreshAllActivities(alias);
            }
        });
    }
}

function onComponentClick(item, alias) {
    dojo.byId(alias + "moduleparent").value = dojo.isArray(item.id) ? item.id[0] : item.id;
    dijit.byId("moduleName" + alias + "module").setValue(item.moduleName);
    dijit.byId("description" + alias + "module").setValue(item.description);
    dojo.byId(alias + "moduleparentnewlevel").value = item.level;
    dijit.byId("moduleName" + alias + "modulenew").reset();
    dijit.byId("description" + alias + "modulenew").reset();
    var level = dojo.isArray(item.level) ? item.level[0] : item.level;
    dijit.byId(alias + "modulesNewLoading").setDisabled(level > 1);
    dijit.byId(alias + "modulesSaveLoading").setDisabled(level == -1);
}

function onNewComponent(alias) {
    var prj = window[alias + "modulesData"].items[0].id;
    newComponent(dojo.isArray(prj) ? prj[0] : prj, dojo.byId(alias + "moduleparent").value, dijit.byId("moduleName" + alias + "modulenew").getValue(), dijit.byId("description" + alias + "modulenew").getValue(), window[alias + "modulesData"], window[alias + "model"], dojo.byId(alias + "moduleparentnewlevel").value, alias);
    dijit.byId("moduleName" + alias + "modulenew").reset();
    dijit.byId("description" + alias + "modulenew").reset();
}

function newVersionMilestone(alias) {
    var prj = window[alias + "modulesData"].items[0].id;
    var version = dojo.byId(alias + "versionparent").value;
    dijit.byId(alias + "versionsNewLoading").setDisabled(true);
    dojo.style(byId(alias + "versionsNewLoadingContainer"), "display", "");
    var label = dijit.byId("label" + alias + "versionNew").getValue();
    var dueDate = dijit.byId("dueDate" + alias + "versionNew").getValue();
    DefaultProjectManager.createVersion(dojo.isArray(prj) ? prj[0] : prj, version, label, dueDate, function(id) {
        dijit.byId(alias + "versionsNewLoading").setDisabled(false);
        dojo.style(byId(alias + "versionsNewLoadingContainer"), "display", "none");
        if (id) {
            dijit.byId("label" + alias + "versionNew").reset();
            dijit.byId("dueDate" + alias + "versionNew").reset();
            var data = window[alias + "versionsData"];
            var model = window[alias + "modelVersion"];
            var item = {id: [id], sequence: [10000+Math.floor(Math.random()*1000)], label: [label], dueDate: [dueDate], level: [version ? 1 : 0], _S: data.items[0]._S, children: []};
            item._S._arrayOfAllItems[item._0] = item;
            if (!version) {
                data.items[0].children.push(item);
                model.onChildrenChange(data.items[0], data.items[0].children);
            } else {
                for (var index = 0; index < data.items[0].children.length; index++) {
                    var milestone = data.items[0].children[index];
                    if (milestone.id == version) {
                        if (!dojo.isArray(milestone.children)) milestone.children = [];
                        milestone.children.push(item);
                        model.onChildrenChange(milestone, milestone.children);
                    }
                }
            }
            updateDashboardGrids();
        }
    });
}

function onVersionClick(alias, item) {
    var level = dojo.isArray(item.level) ? item.level[0] : item.level;
    var current = dojo.isArray(item.current) ? item.current[0] : current;
    var id = dojo.isArray(item.id) ? item.id[0] : item.id;
    var save = dijit.byId(alias + "versionsSaveLoading");
    if (save) {
        save.setDisabled(level == -1);
        dijit.byId(alias + "versionsCurrentLoading").setDisabled(level == -1 || current);
        dijit.byId(alias + "versionsNewLoading").setDisabled(level > 0);
        dojo.byId(alias + "versionparent").value = level == -1 ? null : id;
        dijit.byId("label" + alias + "version").setValue(dojo.isArray(item.label) ? item.label[0] : item.label);
        dijit.byId("dueDate" + alias + "version").setValue(dojo.isArray(item.dueDate) ? item.dueDate[0] : item.dueDate);
        dijit.byId("label" + alias + "versionNew").reset();
        dijit.byId("dueDate" + alias + "versionNew").reset();
    }
    dijit.byId("changelogButton").setDisabled(level < 0);
    byId("changelogId").value = id;
    var versionButton = dijit.byId("targetVersionButton");
    if (versionButton) {
        versionButton.setDisabled(level < 0);
        byId("targetVersionId").value = id;
    }
}

function setAsCurrentVersion(alias) {
    var prj = window[alias + "modulesData"].items[0].id;
    var version = dojo.byId(alias + "versionparent").value;
    dijit.byId(alias + "versionsCurrentLoading").setDisabled(true);
    dojo.style(byId(alias + "versionsLoadingContainer"), "display", "");
    DefaultProjectManager.setAsCurrentVersion(dojo.isArray(prj) ? prj[0] : prj, version, function(done) {
        dijit.byId(alias + "versionsCurrentLoading").setDisabled(done);
        dojo.style(byId(alias + "versionsLoadingContainer"), "display", "none");
        if (done) {
            var data = window[alias + "versionsData"];
            for (var index = 0; index < data.items[0].children.length; index++) {
                var milestone = data.items[0].children[index];
                if (milestone.id == version) {
                    milestone.current = [done];
                } else {
                    milestone.current = [false];
                }
            }
        }
    });
}

function saveVersionChanges(alias) {
    var version = dojo.byId(alias + "versionparent").value;
    var label = dijit.byId("label" + alias + "version").getValue();
    var due = dijit.byId("dueDate" + alias + "version").getValue();
    dijit.byId(alias + "versionsSaveLoading").setDisabled(true);
    dojo.style(byId(alias + "versionsLoadingContainer"), "display", "");
    DefaultProjectManager.changeVersion(version, label, due, function() {
        dijit.byId(alias + "versionsSaveLoading").setDisabled(false);
        dojo.style(byId(alias + "versionsLoadingContainer"), "display", "none");
        var data = window[alias + "versionsData"];
        var model = window[alias + "modelVersion"];
        for (var index = 0; index < data.items[0].children.length; index++) {
            var milestone = data.items[0].children[index];
            if (milestone.id == version) {
                milestone.label = [label];
                milestone.dueDate = [due];
                model.onChange(milestone);
            } else if (dojo.isArray(milestone.children)) {
                for (var inner = 0; inner < milestone.children.length; inner++) {
                    var innerMilestone = milestone.children[inner];
                    if (innerMilestone.id == version) {
                        innerMilestone.label = [label];
                        innerMilestone.dueDate = [due];
                        model.onChange(innerMilestone);
                    }
                }
            }
        }
    });
}

function placebackChangelogSelector() {
    var container = byId(byId("changelogTreeContainer").value);
    var tree = dijit.byId(dojo.byId("changelogTree").value);
    container.appendChild(tree.domNode);
}

function openChangeLogForm(alias) {
    dijit.byId("changelogButton").setDisabled(true);
    byId("changelogId").value = "";
    byId("changelogAlias").value = alias;
    byId("changelogTree").value = alias + "VersionTree";
    byId("changelogTreeContainer").value = alias + "VersionTreeContainer";
    byId("changelogVersionContainer").appendChild(dijit.byId(alias + "VersionTree").domNode);
    openPopup("changelog");
}

function getClosedStatusData(alias, status) {
    var id = dojo.query("input[id*='status']", byId("filterGroup" + alias + "Issues"))[0].id;
    var widget = dijit.byId(id);
    widget.setDisplayedValue(status);
    var data = widget.getValue();
    widget.reset();
    return data;
}

function filterOpenIssues(alias, issueClass, status) {
    var data = getClosedStatusData(alias, status);
    filterByRoadmap(alias, issueClass, [{type: 'ENUM', path: 'status', range: false, invert: true, from: data}]);
}

function filterClosedIssues(alias, issueClass, status) {
    var data = getClosedStatusData(alias, status);
    filterByRoadmap(alias, issueClass, [{type: 'ENUM', path: 'status', range: false, invert: false, from: data}]);
}

function filterByRoadmap(alias, issueClass, filters) {
    window["onSpriteClick" + alias + "IssuesFilter"].call(window);
    filterEntity(alias + "Issues", issueClass, filters);
}

function openSonarConfiguration(id, group, artifact) {
    openPopup("sonarform");
    byId("sonarProject").value = id;
    dijit.byId("mavenGroupIdsonar").setValue(group);
    dijit.byId("mavenArtifactIdsonar").setValue(artifact);
}

function saveSonarConfiguration() {
    dijit.byId("sonarSave").setDisabled(true);
    dojo.html.set(byId("sonarValidationWarningContainer"), "");
    dojo.style(byId("sonarLoadingContainer"), "display", "inline");
    SonarConfigurator.configure(byId("sonarProject").value, componentById("mavenGroupIdsonar").getValue(), componentById("mavenArtifactIdsonar").getValue(), byId("connectionDetailssonar").value, {
        callback: function(data) {
            if (data) {
                dijit.byId("sonarSave").setDisabled(false);
                dojo.style(byId("sonarLoadingContainer"), "display", "none");
                dojo.html.set(byId("sonarValidationWarningContainer"), data);
            } else
                window.location.reload();
        }, errorHandler: function(message) {
            dijit.byId("sonarSave").setDisabled(false);
            dojo.style(byId("sonarLoadingContainer"), "display", "none");
            dojo.html.set(byId("sonarValidationWarningContainer"), message);
        }
    });
}

function openHudsonConfiguration (project, name) {
    openPopup("hudsonform");
    byId("hudsonProject").value = project;
    if (!name || (name == 'null')) dijit.byId("hudsonhudson").reset();
    else dijit.byId("hudsonhudson").setValue(name);
}

function saveHudsonConfiguration() {
    dijit.byId("hudsonSave").setDisabled(true);
    dojo.html.set(byId("hudsonValidationWarningContainer"), "");
    dojo.style(byId("hudsonLoadingContainer"), "display", "inline");
    HudsonConfigurator.configure(byId("hudsonProject").value, byId("connectionDetailshudson").value, componentById("hudsonhudson").getValue(), {
        callback: function(data) {
            if (data) {
                dijit.byId("hudsonSave").setDisabled(false);
                dojo.style(byId("hudsonLoadingContainer"), "display", "none");
                dojo.html.set(byId("hudsonValidationWarningContainer"), data);
            } else
                window.location.reload();
        }, errorHandler: function(message) {
            dijit.byId("hudsonSave").setDisabled(false);
            dojo.style(byId("hudsonLoadingContainer"), "display", "none");
            dojo.html.set(byId("hudsonValidationWarningContainer"), message);
        }
    });
}

function openClosed(open, closed, cht, chd, chxt, chxl, chxp, chxr) {
    var openClosed = new Image();
    var container = byId("openClosedChartContainer");
    dojo.style(container.parentNode, "padding", "0");
    var edge = Math.max(Math.floor(dojo.style(container, "width")), 205);
    var height = Math.floor(dojo.style(container, "height") - 3)
    var src = "http://chart.apis.google.com/chart?chs=" + edge + "x" + height;
    src += "&" + "chg="+ "0,20";
    src += "&" + "cht="+ cht;
    src += "&" + "chd="+ chd;
    src += "&" + "chxt="+ chxt;
    src += "&" + "chxl="+ chxl;
    src += "&" + "chxp="+ chxp;
    src += "&" + "chxr="+ chxr;
    src += "&chdl=" + open + "|" + closed + "&chdlp=b";
    src += "&chco=" + getChartColor() + "," + getSecondChartColor();
    openClosed.src = src;
    container.appendChild(openClosed);
}

function loadPendingIssues(noissues) {
    RemoteIssueManager.getMyPendingIssues(function (data) {
        var container = byId("pendingIssuesContainer");
        if (data && data.length > 0) {
            for (var index = 0; index < data.length; index++) {
                container.appendChild(generatePendingIssue(data[index]));
                if (index != (data.length - 1)) {
                    var hr = document.createElement("hr");
                    dojo.style(hr, "width", "75%");
                    container.appendChild(hr);
                }
            }
        } else {
            container.innerHTML = noissues;
        }
    });
}

function generatePendingIssue(issue) {
    var div = document.createElement("div");
    div.innerHTML = "<div class='overclear'><div class='float_left'><img style='margin-right:8px' src='" + contextPath + "/resource.iwebmvc?file=/images/common/" + issue.type.displayable.toLowerCase() + "_" + currentTheme + ".gif" + "' alt='" + issue.type.displayable + "' title='" + issue.type.displayable + "' /></div><div class='float_left'><a href='javascript:openOrSelectTab(\"" + issue.id + "\", \"" + issue.alias + "\", \"issue\");'><span class='filterQueryLink_" + currentTheme + "' style='text-decoration:underline;font-weight:bold;display:inline-block;margin-top:5px'>" + issue.alias + "</span></a></div><div class='float_right'><img src='" + contextPath + "/resource.iwebmvc?file=/images/common/" + issue.severity.displayable.toLowerCase() + "_" + currentTheme + ".gif" + "' alt='" + issue.severity.displayable + "' title='" + issue.severity.displayable + "' /></div></div><div style='overflow:hidden;height:15px;text-overflow:ellipsis'>" + issue.summary + "</div>";
    return div;
}

function openHudsonConfiguration (project, job) {
    openPopup("hudsonform");
    byId("hudsonProject").value = project;
    dijit.byId("hudsonhudson").setValue(job);
}

function saveHudsonConfiguration() {
    dijit.byId("hudsonSave").setDisabled(true);
    dojo.html.set(byId("hudsonValidationWarningContainer"), "");
    dojo.style(byId("hudsonLoadingContainer"), "display", "inline");
    HudsonConfigurator.configure(byId("hudsonProject").value, byId("connectionDetailshudson").value, componentById("hudsonhudson").getValue(), {
        callback: function(data) {
            if (data) {
                dijit.byId("hudsonSave").setDisabled(false);
                dojo.style(byId("hudsonLoadingContainer"), "display", "none");
                dojo.html.set(byId("hudsonValidationWarningContainer"), data);
            } else
                window.location.reload();
        }, errorHandler: function(message) {
            dijit.byId("hudsonSave").setDisabled(false);
            dojo.style(byId("hudsonLoadingContainer"), "display", "none");
            dojo.html.set(byId("hudsonValidationWarningContainer"), message);
        }
    });
}